package com.beemans.common.ui.views

import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import com.beemans.common.ext.appScreenHeight
import com.beemans.common.ext.appScreenWidth

/**
 * @author tiamosu
 * @date 2021/8/14.
 */
class LocalVisibleDelegate(private val view: View) :
    ViewTreeObserver.OnScrollChangedListener,
    ViewTreeObserver.OnGlobalLayoutListener {

    private val rect by lazy { Rect(0, 0, appScreenWidth, appScreenHeight) }

    var isLocalVisible = false                          //视图处于屏幕可见
        private set
    private var isLastVisibleLocal: Boolean? = null     //记录上一次显示状态
    private var isDetached = false                      //是否销毁

    private var callback: ((isLocalVisible: Boolean) -> Unit)? = null

    override fun onScrollChanged() {
        onLocalVisibleChange()
    }

    override fun onGlobalLayout() {
        onLocalVisibleChange()
    }

    /**
     * 视图在屏幕可见变化
     */
    private fun onLocalVisibleChange() {
        if (isDetached) return
        isLocalVisible = view.getLocalVisibleRect(rect)
        if (isLastVisibleLocal == isLocalVisible) return
        isLastVisibleLocal = isLocalVisible

        callback?.invoke(isLocalVisible)
    }

    fun onViewLocalVisible(callback: (isLocalVisible: Boolean) -> Unit) {
        this.callback = callback
    }

    fun onAttachedToWindow() {
        isDetached = false
        view.viewTreeObserver.apply {
            if (!isAlive) return@apply
            addOnGlobalLayoutListener(this@LocalVisibleDelegate)
            addOnScrollChangedListener(this@LocalVisibleDelegate)
        }
    }

    fun onDetachedFromWindow() {
        isDetached = true
        isLocalVisible = false
        isLastVisibleLocal = null
        view.viewTreeObserver.apply {
            if (!isAlive) return@apply
            removeOnGlobalLayoutListener(this@LocalVisibleDelegate)
            removeOnScrollChangedListener(this@LocalVisibleDelegate)
        }
    }
}